package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.node.impl.ActionNode;
import com.sparrow.common.ai.findpath.impl.AStar;
import com.sparrow.common.map.Position;
import com.sparrow.common.util.RandomUtil;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.impl.Monster;
import com.study.example.gameserver.module.scene.service.SceneService;

import java.util.List;

import static com.sparrow.common.aoi.util.MapUtil.toPositionList;
import static com.sparrow.common.aoi.util.MapUtil.worldToGrid;

/**
 * 巡逻路径（随机目标点 → A* 寻路 → 设置路径）
 * 支持格子坐标 ↔ 世界坐标自动转换
 */
public class PatrolPath extends ActionNode {

    private static final int MAX_RETRY = 5; // 随机点最多尝试次数

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        Monster monster = context.getOwner();
        if (monster == null) {
            return BTNodeStatus.FAILURE;
        }

        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null) {
            return BTNodeStatus.FAILURE;
        }

        // 随机生成合法目标点
        Position targetWorld = null;
        for (int i = 0; i < MAX_RETRY; i++) {
            Position candidate = randomPatrolPos(monster.getSpawn());
            int[] grid = worldToGrid(candidate);
            if (sceneMap.getMapData().isWalkable(grid[0], grid[1])) {
                targetWorld = candidate;
                break;
            }
        }
        if (targetWorld == null) {
            return BTNodeStatus.FAILURE;
        }

        // 世界坐标 → 格子坐标
        int[] start = worldToGrid(monster.getPos());
        int[] end = worldToGrid(targetWorld);

        // A* 寻路（格子）
        AStar aStar = monster.getAStar();
        List<int[]> path = aStar.findPath(sceneMap.getMapData().getWalkable(), start, end);
        if (path == null || path.isEmpty()) {
            return BTNodeStatus.FAILURE;
        }

        // 格子路径 → 世界坐标路径
        List<Position> roads = toPositionList(path);
        monster.setRoads(roads);
        monster.setRoadIndex(1);
        monster.updateAngle();
//        System.out.println("巡逻 A* 格子路径= " + JsonUtil.toJSON(path));
        SceneService sceneService = context.get("SceneMapService", SceneService.class);
        sceneService.sendMonsterInfo(monster);
        return BTNodeStatus.SUCCESS;
    }



    /** 随机生成巡逻目标点（世界坐标） */
    private Position randomPatrolPos(Position spawn) {
        float offsetX = (RandomUtil.nextFloat() - 0.4f) * 10; // 5x5 范围
        float offsetZ = (RandomUtil.nextFloat() - 0.4f) * 10;
        return new Position(spawn.getX() + offsetX, 0, spawn.getZ() + offsetZ);
    }
}
